package com.example.sprintboot.service.impl;

import com.example.sprintboot.entity.Category;
import com.example.sprintboot.mapper.CategoryMapper;
import com.example.sprintboot.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> getCategoryTree() {
        List<Category> all = categoryMapper.selectAll();
        Map<Integer, Category> map = all.stream().collect(Collectors.toMap(Category::getCategoryId, c -> c));
        List<Category> roots = new ArrayList<>();
        for (Category c : all) {
            if (c.getParentId() == 0) {
                roots.add(c);
            } else {
                Category parent = map.get(c.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) parent.setChildren(new ArrayList<>());
                    parent.getChildren().add(c);
                }
            }
        }
        return roots;
    }

    @Override
    public List<Category> getAllCategories() {
        return categoryMapper.selectAll();
    }

    @Override
    public Category getCategoryById(Integer categoryId) {
        return categoryMapper.selectById(categoryId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCategory(Category category) {
        // 验证分类名称不能为空
        if (category.getName() == null || category.getName().trim().isEmpty()) {
            return false;
        }
        
        // 设置默认值
        if (category.getParentId() == null) {
            category.setParentId(0); // 默认为根分类
        }
        if (category.getLevel() == null) {
            // 计算层级
            if (category.getParentId() == 0) {
                category.setLevel(1);
            } else {
                Category parent = categoryMapper.selectById(category.getParentId());
                if (parent != null) {
                    category.setLevel(parent.getLevel() + 1);
                } else {
                    category.setLevel(1);
                }
            }
        }
        if (category.getIsLeaf() == null) {
            category.setIsLeaf(1); // 默认为叶子节点
        }
        
        // 检查同级分类名称是否重复
        List<Category> siblings = categoryMapper.selectByParentId(category.getParentId());
        boolean nameExists = siblings.stream()
                .anyMatch(c -> c.getName().equals(category.getName()));
        if (nameExists) {
            return false;
        }
        
        // 插入分类
        int result = categoryMapper.insert(category);
        
        // 如果添加成功且不是根分类，更新父分类的isLeaf状态
        if (result > 0 && category.getParentId() != 0) {
            Category parent = categoryMapper.selectById(category.getParentId());
            if (parent != null && parent.getIsLeaf() == 1) {
                parent.setIsLeaf(0);
                categoryMapper.updateById(parent);
            }
        }
        
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCategory(Category category) {
        // 验证分类是否存在
        Category existingCategory = categoryMapper.selectById(category.getCategoryId());
        if (existingCategory == null) {
            return false;
        }
        
        // 验证分类名称不能为空
        if (category.getName() == null || category.getName().trim().isEmpty()) {
            return false;
        }
        
        // 检查同级分类名称是否重复（排除自己）
        List<Category> siblings = categoryMapper.selectByParentId(existingCategory.getParentId());
        boolean nameExists = siblings.stream()
                .anyMatch(c -> c.getName().equals(category.getName()) && !c.getCategoryId().equals(category.getCategoryId()));
        if (nameExists) {
            return false;
        }
        
        // 更新分类
        return categoryMapper.updateById(category) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCategory(Integer categoryId) {
        // 检查分类是否存在
        Category category = categoryMapper.selectById(categoryId);
        if (category == null) {
            return false;
        }
        
        // 检查是否有子分类
        List<Category> children = categoryMapper.selectByParentId(categoryId);
        if (!children.isEmpty()) {
            return false; // 有子分类，不能删除
        }
        
        // 检查是否有商品使用此分类
        int productCount = categoryMapper.countProductsByCategoryId(categoryId);
        if (productCount > 0) {
            return false; // 有商品使用此分类，不能删除
        }
        
        // 删除分类
        int result = categoryMapper.deleteById(categoryId);
        
        // 如果删除成功且不是根分类，检查父分类是否还有其他子分类
        if (result > 0 && category.getParentId() != 0) {
            List<Category> remainingChildren = categoryMapper.selectByParentId(category.getParentId());
            if (remainingChildren.isEmpty()) {
                // 父分类没有其他子分类了，设置为叶子节点
                Category parent = categoryMapper.selectById(category.getParentId());
                if (parent != null) {
                    parent.setIsLeaf(1);
                    categoryMapper.updateById(parent);
                }
            }
        }
        
        return result > 0;
    }

    @Override
    public List<Category> getParentCategories() {
        // 获取所有可以作为父分类的分类（非叶子节点或根分类）
        return categoryMapper.selectParentCategories();
    }
} 